package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.base.utils.JwtUtils;
import com.atguigu.srb.core.enums.BorrowAuthEnum;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowInfoVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2023-01-04
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {
    @Resource
    DictService dictService;
    @Resource
    UserInfoService userInfoService;
    @Resource
    BorrowerService borrowerService;
    @Resource
    LendService lendService;
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo,String token) {
        Long userId = JwtUtils.getUserId(token);
        //验证用户借款金额不能超过自己允许的额度： 自己完成

        borrowInfo.setUserId(userId);
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        //将前端提交的 %比的年化率转为小数存储
        BigDecimal decimal = borrowInfo.getBorrowYearRate().divide(new BigDecimal(100), 8,
                BigDecimal.ROUND_DOWN);
        borrowInfo.setBorrowYearRate(decimal);

        this.save(borrowInfo);

    }

    @Override
    public Integer getBorrowStatus(String token) {
        Long userId = JwtUtils.getUserId(token);
        //查询当前用户借款信息的状态
        BorrowInfo borrowInfo = this.getOne(Wrappers.lambdaQuery(BorrowInfo.class)
                .eq(BorrowInfo::getUserId, userId)
                .orderByDesc(BorrowInfo::getCreateTime)
                .last("limit 1"));
        if(borrowInfo==null || borrowInfo.getStatus()==3){
            return 0;
        }
        return borrowInfo.getStatus();
    }

    @Override
    public List<BorrowInfoVO> getBorrowInfos() {
        List<BorrowInfo> borrowInfos = this.list();
        //将每一个borroInfo对象转为一个BorrowInfoVO对象
        List<BorrowInfoVO> borrowInfoVOS = borrowInfos.stream().map(borrowInfo -> {
            return getBorrowInfoVO(borrowInfo);
        }).collect(Collectors.toList());
        return borrowInfoVOS;
    }

    private BorrowInfoVO getBorrowInfoVO(BorrowInfo borrowInfo) {
        BorrowInfoVO borrowInfoVO = new BorrowInfoVO();
        BeanUtils.copyProperties(borrowInfo,borrowInfoVO);
        borrowInfoVO.setBorrowYearRate(borrowInfo.getBorrowYearRate()
                .multiply(new BigDecimal(100)).toString()+"%");

        Dict dict = dictService.getDictByDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        borrowInfoVO.setMoneyUse(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        borrowInfoVO.setReturnMethod(dict.getName());
        switch(borrowInfo.getStatus()){
            case 0:
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.NO_AUTH.getMsg());
                break;
            case 1:
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getMsg());
                break;
            case 2:
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.CHECK_OK.getMsg());
                break;
            default:
                borrowInfoVO.setStatus(BorrowInfoStatusEnum.CHECK_FAIL.getMsg());
                break;
        }

        UserInfo userInfo = userInfoService.getById(borrowInfo.getUserId());
        borrowInfoVO.setName(userInfo.getName());
        borrowInfoVO.setMobile(userInfo.getMobile());
        return borrowInfoVO;
    }

    @Override
    public Map<String, Object> getBorrowInfo(String id) {
        BorrowInfo borrowInfo = this.getById(id);
        BorrowInfoVO borrowInfoVO = getBorrowInfoVO(borrowInfo);

        Borrower borrower = borrowerService.getOne(Wrappers.lambdaQuery(Borrower.class)
                .eq(Borrower::getUserId, borrowInfo.getUserId())
                .select(Borrower::getId));
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetailById(borrower.getId().toString());

        Map<String, Object> map = new HashMap<>();
        map.put("borrowInfoVO",borrowInfoVO);
        map.put("borrowerDetailVO",borrowerDetailVO);
        return map;
    }

    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        //1、更新借款信息审批状态： 根据借款id更新
        Long id = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = this.getById(id);
        borrowInfo.setUpdateTime(null);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        this.updateById(borrowInfo);
        if(borrowInfoApprovalVO.getStatus()!=
            BorrowInfoStatusEnum.CHECK_OK.getStatus()){//审批未通过
            return;
        }
        //2、如果审批通过：生成新的标的
        lendService.createLend(borrowInfo,borrowInfoApprovalVO);

    }
}
